//
//  UserMineHeadView.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/3/17.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "UserMineHeadView.h"
#import "ApplySalesmanView.h"
#import "ApplySalesmanView.h"

extern UserModel *userModel;
@interface UserMineHeadView ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UITextViewDelegate,UIGestureRecognizerDelegate>{
    UIImagePickerController *_imagePicker; // 图片选择控制器
    BOOL _IsCamera; // 是否调用相机
    UIImage *_image;

}


@end

@implementation UserMineHeadView

+(instancetype)getView {
    
    return [[[NSBundle mainBundle] loadNibNamed:@"UserMineHeadView" owner:nil options:nil] lastObject];
    
}

- (void)awakeFromNib {
    
    [super awakeFromNib];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadUsetInfo) name:kUserInfoDetailsUpDate object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setExitAppUi) name:kUserInfoDetailsExitUpDate object:nil];
    
    self.headImageView.layer.cornerRadius = 28;
    self.headImageView.clipsToBounds = YES;
    self.yinkaImgView.hidden  = YES;

    
    if ([CommonTTool isJumpLoginVC:NO]) {
        [self setUi];
    }else {
//        SD_SETIMAGE_PlaceHolder(self.headImageView, @"", @"defHead")
    }
    
}

- (void)setExitAppUi {

    
    SD_SETIMAGE_PlaceHolder(self.headImageView, @"", @"defHead")
    self.loginBtn.hidden = NO;
    self.nameLabel.hidden = YES;
    self.tuiguangLabel.hidden = YES;
    self.shenqingBtn.hidden = YES;
    self.yinkaImgView.hidden  = YES;

}


- (void)setUi {
    
    NSString *url = userModel.head_img_path;
    if (![CommonTTool isStrNull:url]) {
        SD_SETIMAGE_PlaceHolder(self.headImageView, url, @"defHead")
    }
    if ([CommonTTool isStrNull:userModel.name]) {
        self.nameLabel.text = @"未填写";

    }else {
        self.nameLabel.text = userModel.name;
    }
    self.tuiguangLabel.text = [NSString stringWithFormat:@"推广码：%@[复制]",userModel.my_code];
    
    self.headImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *imageTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(headImageTap)];
    [self.headImageView addGestureRecognizer:imageTap];
    
    [self upDateUi];
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(uploadUsetInfo) name:@"upDateShenQing" object:nil];
    
    UITapGestureRecognizer *codeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(codeTap)];
    self.tuiguangLabel.userInteractionEnabled = YES;
    [self.tuiguangLabel addGestureRecognizer:codeTap];
    
    if (userModel.vip_type == 2) {
        self.yinkaImgView.hidden  = NO;
    }
    
}

- (void)codeTap  {
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];

    pasteboard.string = userModel.my_code;
    
    SVP(@"推广码已复制至剪贴板");
}

- (void)upDateUi {
    
    if ([userModel.sh_state isEqualToString:@"1"]) {
        [self.shenqingBtn setTitle:@"申请业务员" forState:UIControlStateNormal];
        
    }
    if ([userModel.sh_state isEqualToString:@"2"]) {
       [self.shenqingBtn setTitle:@"申请业务员" forState:UIControlStateNormal];
    }
    
    if ([userModel.sh_state isEqualToString:@"3"]) {
       [self.shenqingBtn setTitle:@"业务员" forState:UIControlStateNormal];
    }
    
    if ([userModel.sh_state isEqualToString:@"4"]) {
       [self.shenqingBtn setTitle:@"申请业务员" forState:UIControlStateNormal];
    }
    
    
    
}


- (IBAction)shenQingBtnClick:(id)sender {
    
    if ([userModel.sh_state isEqualToString:@"1"]) {
        [ApplySalesmanView showView];
    }
    if ([userModel.sh_state isEqualToString:@"2"]) {
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"" message: @"我们将在7个工作日内完成审核，如未审核通过请直接电话联系我们" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction: [UIAlertAction actionWithTitle:@"审核中" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
           [CommonTTool serviceCallPhone];
        }]];
        [[CommonTTool getCurrentVC] presentViewController: alertController animated: YES completion: nil];
    }
    
    if ([userModel.sh_state isEqualToString:@"3"]) {
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"" message: @"您的审核已通过，具体业务请联系我们" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
        [alertController addAction: [UIAlertAction actionWithTitle:@"确定" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
           [CommonTTool serviceCallPhone];
        }]];
        [[CommonTTool getCurrentVC] presentViewController: alertController animated: YES completion: nil];
    }
    
    if ([userModel.sh_state isEqualToString:@"4"]) {
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"" message: @"您的审核未通过，请直接电话联系我们" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
        [alertController addAction: [UIAlertAction actionWithTitle:@"确定" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            [CommonTTool serviceCallPhone];
           
        }]];
        [[CommonTTool getCurrentVC] presentViewController: alertController animated: YES completion: nil];
    }
    
    
    
}


- (void)headImageTap {
    
    [self create_ActionSheet];
    
    
}


#pragma mark - 点击换头像事件
- (void)create_ActionSheet {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"选择" message: nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction: [UIAlertAction actionWithTitle: @"拍照" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self use_camera];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle:@"我的相册" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self pickPhoto];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [[CommonTTool getCurrentVC] presentViewController: alertController animated: YES completion: nil];
}

#pragma mark - 调用相机
- (void)use_camera {
    _IsCamera = YES;
    UIImagePickerController *imageController = [[UIImagePickerController alloc]init];
    imageController.delegate = self;
    imageController.allowsEditing = YES ;
    imageController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [[CommonTTool getCurrentVC] presentViewController:imageController animated:YES completion:nil];
}

#pragma mark - 点击从本地相册调用图片
- (void)pickPhoto {
    _IsCamera = NO;
    UIImagePickerController *imagePickerTemp = [[UIImagePickerController alloc]init];
    _imagePicker = imagePickerTemp;
    _imagePicker.delegate = self;
    _imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    _imagePicker.allowsEditing = YES;
    [[CommonTTool getCurrentVC] presentViewController:_imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    //    info.fileType
        UIImage *headerImg;
    if (_IsCamera) {
       
        headerImg = [info objectForKey:UIImagePickerControllerOriginalImage];
        if(headerImg.imageOrientation!=UIImageOrientationUp){
            // Adjust picture Angle
            UIGraphicsBeginImageContext(CGSizeMake(headerImg.size.width * 0.4, headerImg.size.height * 0.4));
            [headerImg drawInRect:CGRectMake(0, 0,headerImg.size.width * 0.4, headerImg.size.height * 0.4)];
            headerImg = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        headerImg = [CommonTTool imageCompression:headerImg];
        CGSize size = headerImg.size;
        NSLog(@"高%f----宽%f",size.height,size.width);
        
    }else {
       
        headerImg = [info objectForKey:UIImagePickerControllerEditedImage];
        CGSize size = headerImg.size;
        NSLog(@"高%f----宽%f",size.height,size.width);
    }
    
    [self uploadHeadImage:headerImg]; // 图片上传接口
    //     _image = [info objectForKey: UIImagePickerControllerEditedImage];
    
}

- (void)uploadHeadImage:(UIImage *)image {
    __weak typeof(self) weakSelf = self;
    NSArray *imageArray = [NSArray arrayWithObjects:image, nil];
    [NetManager isUpdateImgArr:imageArray andData:nil andFileName:nil success:^(NSDictionary *dic) {
//        weakSelf.model.headPortraitImg = dic [@"object"];
//        [self.baseTableview reloadData];
        NSString *imagePath = dic[@"object"];

        userModel.head_img_path = imagePath;
       
        [self setUserHeead];
    } uploadProgress:^(NSProgress *_Nonnull str) {

    }];
    
//    NSDictionary *parameters = @{
//    @"bucket":@"ofaimg", // 类型 1 图片 2 视频
//    };
//
//    [NetRequestTool upLoadImage:UpdateImageAliyunFile parameters:parameters image:image success:^(id responseObject) {
//            NSString *imagePath = responseObject[@"object"];
//
//            userModel.head_img_path = imagePath;
//            SD_SETIMAGE_PlaceHolder(weakSelf.headImageView, imagePath, @"default_image_square");
//            NSLog(@"%@",responseObject);
//            [self uploadUsetInfo];
//    } failure:^{
//
//    } finish:^{
//
//    }];
    
}

- (void)setUserHeead {
    
    NSDictionary *dict = @{@"head_img_path": userModel.head_img_path,
                           @"access_token":[LEUserManager token]
    };
    
    SVPShowInternetWaiting
    [NetManager isUpdateUserInfoWithParameters:dict success:^{
        SD_SETIMAGE_PlaceHolder(self.headImageView, userModel.head_img_path, @"default_image_square");
               
        [self uploadUsetInfo];
        
    }];
    
}

- (void)uploadUsetInfo {
    [NetRequestTool postUrl:@"user/getUserInfo" parameters:@{} success:^(id responseObject) {
         
        NSDictionary *dic = responseObject[@"object"];
        [[NSUserDefaults standardUserDefaults] setObject:[dic deleteNull] forKey:kUserInfo];
        
        userModel = [UserModel mj_objectWithKeyValues:dic];
        [self setUi];
       
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
        SVPDismiss
    }];
}



@end

